package com.paomi.client.activity.pay;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;

import com.google.gson.JsonSyntaxException;
import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter;
import com.paomi.client.R;
import com.paomi.client.activity.detail.model.EnterTypeBean;
import com.paomi.client.activity.pay.adapter.EnterListAdapter;
import com.paomi.client.activity.pay.adapter.MyCardListAdapter;
import com.paomi.client.activity.pay.model.AddressBean;
import com.paomi.client.activity.pay.model.CardCouponBean;
import com.paomi.client.activity.pay.model.PaySureBean;
import com.paomi.client.activity.pay.model.SendMoneyBean;
import com.paomi.client.activity.payMoney.PayMoneyActivity;
import com.paomi.client.activity.person.model.CardJsonBean;
import com.paomi.client.activity.person.model.TicketBalanceBean;
import com.paomi.client.activity.takeTicket.TakeTicketListActivity;
import com.paomi.client.activity.takeTicket.model.TakeTicketBean;
import com.paomi.client.activity.takeTicket.model.TicketPersonBean;
import com.paomi.client.net.Api;
import com.paomi.client.net.BaseCallback;
import com.paomi.client.net.Constants;
import com.paomi.client.utils.UIUtils;
import com.paomi.client.view.LoadingDialog;
import com.paomi.client.widget.RxToast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by pc on 2018/11/12
 * Describe:
 * com.paomi.client.activity.pay
 */
public class PayPresenter extends MvpBasePresenter<PayMvpView> {
    //请求默认收货地址的接口
    public void getAddress() {
        LoadingDialog.get().showLoading();
        Api.getInstanceService(Constants.User_URL).getAddressPay().enqueue(new BaseCallback<AddressBean>() {
            @Override
            public void onResponse(Call<AddressBean> call, AddressBean result) {
                getView().setAddressData(result);
                LoadingDialog.get().hideLoading();
            }
        });
    }

    /**
     * 获得积分余额
     *
     * @param goodsId
     */
    public void getIntergalBalance(String goodsId) {
        Api.getInstanceService(Constants.User_URL).getTicketBalance(goodsId).enqueue(new Callback<TicketBalanceBean>() {
            @Override
            public void onResponse(Call<TicketBalanceBean> call, Response<TicketBalanceBean> response) {
                getView().setIntergalBanlance(response.body());
            }

            @Override
            public void onFailure(Call<TicketBalanceBean> call, Throwable t) {
                getView().setIntergalBanlance(null);
            }
        });

    }

    /**
     * 获得运费(快递费)
     *
     * @param goodsId
     */
    public void getCalculatePass(String goodsId, String addressId, String num) {
        Api.getInstanceService(Constants.Pay_URL).sendMoneyCalcul(goodsId, addressId, num).enqueue(new Callback<SendMoneyBean>() {
            @Override
            public void onResponse(Call<SendMoneyBean> call, Response<SendMoneyBean> response) {
                getView().setPassMoney(response.body());
            }

            @Override
            public void onFailure(Call<SendMoneyBean> call, Throwable t) {

            }
        });

    }

    /**
     * 选择优惠券的弹框
     *
     * @param activity
     * @param typeface
     * @param sumMoney//票价总额
     */
    public void showDialogCoupon(Activity activity, Typeface typeface, String getId,float sumMoney) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_coupon_show, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);
        dialog.show();
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
        lp.height = activity.getResources().getDisplayMetrics().heightPixels / 5 * 3;
//        lp.height=WindowManager.LayoutParams.WRAP_CONTENT;   //设置高度
        window.setAttributes(lp);
        LinearLayout ll_none = view.findViewById(R.id.ll_none);
        RecyclerView couponList = view.findViewById(R.id.coupon_list);
        couponList.setLayoutManager(UIUtils.getRecyclerViewManager(false, activity));
        List<CardJsonBean> list = new ArrayList<>();
        MyCardListAdapter adapter = new MyCardListAdapter(activity, typeface,sumMoney);
        couponList.setAdapter(adapter);
//        adapter.setOnItemClickListener(new MyCardListAdapter.OnItemClickListener() {
//            @Override
//            public void setOnItemClick(int pos) {//得到卡券返回值
//
//            }
//        });

        Api.getInstanceService(Constants.User_URL).getCouponCardPay("1", getId).enqueue(new BaseCallback<CardCouponBean>() {
            @Override
            public void onResponse(Call<CardCouponBean> call, CardCouponBean result) {
                list.clear();
                list.addAll(result.getReturnData());
                if (list.size() > 0) {
                    ll_none.setVisibility(View.GONE);
                    //不默认选择第一张
//                    for (int i = 0; i < list.size(); i++) {
//                        if(i==0){
//                            list.get(i).setSelect(1);
//                        }else{
//                            list.get(i).setSelect(0);
//                        }
//
//                    }
                    adapter.setData(list);
                } else {
                    ll_none.setVisibility(View.VISIBLE);
                }
                if (list.size() > 0) {
                    ll_none.setVisibility(View.GONE);
                } else {
                    //代表没有可选择的卡券
                    ll_none.setVisibility(View.VISIBLE);
//            getView().setCouponData(null);
                }
                adapter.notifyDataSetChanged();
            }
        });

        Button button = view.findViewById(R.id.check_coupon);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                button.setBackgroundColor(activity.getResources().getColor(R.color.main_color));
                button.setTextColor(activity.getResources().getColor(R.color.white));
                button.getBackground().setAlpha(100);
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getSelect() == 1) {
                        CardJsonBean couponBean = list.get(i);
                        getView().setCouponData(couponBean);
                        break;
                    }else{
                        getView().setCouponData(null);
                    }
                }
            }
        });
    }

    /**
     * 默认选择优惠券
     * @param getId
     */
    public void choiceCoupon(String getId){
        List<CardJsonBean> list = new ArrayList<>();
        Api.getInstanceService(Constants.User_URL).getCouponCardPay("1", getId).enqueue(new BaseCallback<CardCouponBean>() {
            @Override
            public void onResponse(Call<CardCouponBean> call, CardCouponBean result) {
                list.clear();
                list.addAll(result.getReturnData());
                getView().setCouponChoice(list);
            }
        });
    }

    private EnterTypeBean enterBean;

    /**
     * 选择配送方式的弹框
     *
     * @param activity
     * @param typeface
     */
    public void showDialogShip(Activity activity, Typeface typeface, TakeTicketBean takeTicketBean, List<EnterTypeBean> enterTypeList) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_express_method, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);
        dialog.show();
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
        lp.height = activity.getResources().getDisplayMetrics().heightPixels / 5 * 3;
//        lp.height=WindowManager.LayoutParams.WRAP_CONTENT;   //设置高度
        window.setAttributes(lp);
        Button button = view.findViewById(R.id.check_coupon);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (takeTicketBean == null) {
                    return;
                }
                dialog.dismiss();
                button.setBackgroundColor(activity.getResources().getColor(R.color.main_color));
                button.setTextColor(activity.getResources().getColor(R.color.white));
                button.getBackground().setAlpha(100);
            }
        });
        RecyclerView recyclerView = view.findViewById(R.id.entry_list);
        recyclerView.setLayoutManager(UIUtils.getRecyclerViewManager(false, activity));
        EnterListAdapter enterListAdapter = new EnterListAdapter(activity, typeface);
        recyclerView.setAdapter(enterListAdapter);
        if (enterTypeList.size() > 0) {
            //选中
            enterListAdapter.OnItemClick(new EnterListAdapter.OnItemClick() {
                @Override
                public void setOnCheckClick(View view, int pos) {
                }

                //取票人信息页面的跳转
                @Override
                public void setOnItemClick(View view, int pos) {
                    dialog.dismiss();
                    enterBean = (EnterTypeBean) view.getTag();
                    activity.startActivityForResult(new Intent(activity, TakeTicketListActivity.class), 8001);
                }
            });
            if (enterBean != null && takeTicketBean != null) {
                for (int i = 0; i < enterTypeList.size(); i++) {
                    EnterTypeBean typeBean = enterTypeList.get(i);
                    if (enterBean.getValue().equals(typeBean.getValue())) {
                        typeBean.setGetName(takeTicketBean.getName() + "," + takeTicketBean.getCode());
                    }
                }

            }
            enterListAdapter.setData(enterTypeList);
            enterListAdapter.notifyDataSetChanged();
        }
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < enterTypeList.size(); i++) {
                    if (enterTypeList.get(i).getType() == 1) {
                        getView().setEnterData(enterTypeList.get(i));
                    }
                }
                dialog.dismiss();
            }
        });
    }

    /**
     * @param activity goodsId	true	演出项目ID
     *                 goodsPlanId	true	演出场次ID
     *                 goodsTicketJson	true	演出座次Json串。key goodsTicketId ， value 数量。 {'112107' : '3', '112108':'1'}
     *                 coolectTicketType	true	取票方式
     *                 userAddressId	false	收货地址
     *                 realNameIds	false	购票人ID 多个以 英文逗号分隔
     *                 integral	false	用户使用的积分数
     *                 userCouponId	false	优惠券ID
     *                 collectName	false	取票方式为现场取票时必-取票人姓名
     *                 collectPhone	false	取票方式为现场取票时必选-联系方式
     *                 orderType	true	取票方式 0 主办方系统订单 1 出票系统订单
     */
    public void setOrderSure(Activity activity, String goodsId, String goodsPlanId,
                             String goodsTicketJson, String coolectTicketType, String userAddressId,
                             String realNameIds, String integral, String userCouponId
            , String collectName, String collectPhone, String orderType) {
        Map<String, String> maps = new HashMap<>();
        maps.put("goodsId", goodsId);
        maps.put("goodsPlanId", goodsPlanId);
        maps.put("goodsTicketJson", goodsTicketJson);
        maps.put("coolectTicketType", coolectTicketType);
        maps.put("userAddressId", userAddressId);
        maps.put("realNameIds", realNameIds);
        maps.put("integral", integral);
        maps.put("userCouponId", userCouponId);
        maps.put("collectName", collectName);
        maps.put("collectPhone", collectPhone);
        maps.put("orderType", orderType);
        Api.getInstanceService(Constants.Pay_URL).sureOrderPlace(maps).enqueue(new BaseCallback<PaySureBean>() {
            @Override
            public void onResponse(Call<PaySureBean> call, PaySureBean result) {
                Intent intent = new Intent(activity, PayMoneyActivity.class);
                intent.putExtra("paySure", result.getReturnData());
                intent.putExtra("goodId", goodsId);
                activity.startActivity(intent);
                activity.finish();
            }
        });
    }

    /**
     * 实质购票人列表
     *
     * @param page
     */
    public void getTicketPersonList(int page) {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", "" + page);
        map.put("pageSize", "" + 20);
        Api.getInstanceService(Constants.User_URL).getTicketTakePay(map).enqueue(new BaseCallback<TicketPersonBean>() {
            @Override
            public void onResponse(Call<TicketPersonBean> call, TicketPersonBean result) {
                getView().setPersonList(result);
            }
        });
    }
}
